//
//  ZODHTTPManager.m
//  ZTEOnlineDoc
//
//  Created by 万伟琦 on 2018/9/12.
//  Copyright © 2018年 ZTE. All rights reserved.
//

#import "ZODHTTPManager.h"
#import "ZODInternalTools.h"

@interface ZODHTTPManager ()

@property (nonatomic) NSOperationQueue *opQueue;
@property (nonatomic, assign) NSInteger timeout;

@end

@implementation ZODHTTPManager

- (instancetype)init {
    if (self = [super init]) {
        _opQueue = [[NSOperationQueue alloc] init];
        _opQueue.maxConcurrentOperationCount = 5;
        _timeout = 10;
    }
    return self;
}

+ (instancetype)sharedManager {
    static ZODHTTPManager *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[ZODHTTPManager alloc] init];
    });
    return instance;
}


- (void)POST:(NSString *)urlStr withParameters:(NSDictionary *)paras completion:(void (^)(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error))completion {
    
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        
        NSURLSession *session = [NSURLSession sharedSession];
        NSURL *url = [[NSURL alloc] initWithString:urlStr];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:self.timeout];
        request.HTTPMethod = @"POST";
        request.HTTPBody = [ZODInternalTools JSONDataFromDictionary:paras];
        
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:completion];
        [dataTask resume];
    }];
    
    [self.opQueue addOperation:operation];
}

- (void)GET:(NSString *)urlStr withParameters:(NSDictionary *)paras completion:(void (^)(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error))completion {
  
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        
        NSURL *url = [ZODInternalTools composeGETURLWithBaseURL:urlStr parameters:paras];
        
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:self.timeout];
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:completion];
        [dataTask resume];
    }];
    
    [self.opQueue addOperation:operation];
}

@end
